#!/bin/bash

set -e  # 遇到错误立即退出

echo "正在检测系统版本..."

# 检查是否为 CentOS 系统
if [ ! -f /etc/redhat-release ]; then
    echo "错误：此系统不是 CentOS"
    exit 1
fi

# 检查是否为 CentOS 7 系列
if ! grep -q "CentOS Linux release 7" /etc/redhat-release && ! grep -q "CentOS release 7" /etc/redhat-release; then
    echo "错误：此系统不是 CentOS 7"
    exit 1
fi

# 提取版本号
CENTOS_VERSION=$(grep -oE 'release [0-9]+\.[0-9]+' /etc/redhat-release | grep -oE '[0-9]+\.[0-9]+')

# 验证版本范围 (7.0 - 7.9)
if [[ ! "$CENTOS_VERSION" =~ ^7\.[0-9]$ ]]; then
    echo "错误：此脚本仅支持 CentOS 7.0-7.9，当前系统版本为 CentOS $CENTOS_VERSION"
    exit 1
fi

echo "检测到系统为 CentOS $CENTOS_VERSION，开始配置镜像源..."

# 备份原有配置
echo "备份原有 yum 配置..."
BACKUP_DIR="/etc/yum.repos.d/backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"
cp /etc/yum.repos.d/CentOS-*.repo "$BACKUP_DIR/" 2>/dev/null || true

echo "备份完成，文件保存在: $BACKUP_DIR"

# 创建综合配置（修复注释问题）
cat > /etc/yum.repos.d/centos-all-mirrors.repo << 'EOF'
[base]
name=CentOS-7 - Base
failovermethod=priority
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/os/x86_64/
        https://mirrors.huaweicloud.com/centos/7/os/x86_64/
        https://mirrors.aliyun.com/centos/7/os/x86_64/
        https://mirrors.bfsu.edu.cn/centos/7/os/x86_64/
        https://mirrors.shu.edu.cn/centos/7/os/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

# 注意：vault 源用于旧版本软件包，当主镜像站移除旧包时使用
[base-vault]
name=CentOS-7 - Base Vault
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos-vault/7.$releasever/os/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=0

[updates]
name=CentOS-7 - Updates
failovermethod=priority
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/updates/x86_64/
        https://mirrors.huaweicloud.com/centos/7/updates/x86_64/
        https://mirrors.aliyun.com/centos/7/updates/x86_64/
        https://mirrors.bfsu.edu.cn/centos/7/updates/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[updates-vault]
name=CentOS-7 - Updates Vault
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos-vault/7.$releasever/updates/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=0

[extras]
name=CentOS-7 - Extras
failovermethod=priority
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/extras/x86_64/
        https://mirrors.huaweicloud.com/centos/7/extras/x86_64/
        https://mirrors.aliyun.com/centos/7/extras/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[centosplus]
name=CentOS-7 - Plus
failovermethod=priority
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/centosplus/x86_64/
        https://mirrors.huaweicloud.com/centos/7/centosplus/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=0

[epel]
name=EPEL 7
failovermethod=priority
baseurl=https://mirrors.tuna.tsinghua.edu.cn/epel/7/x86_64/
        https://mirrors.huaweicloud.com/epel/7/x86_64/
        https://mirrors.aliyun.com/epel/7/x86_64/
gpgcheck=1
gpgkey=https://mirrors.tuna.tsinghua.edu.cn/epel/RPM-GPG-KEY-EPEL-7
enabled=1
EOF

# 禁用原有的 CentOS 源（重命名而不是删除）
for repo in /etc/yum.repos.d/CentOS-*.repo; do
    if [ -f "$repo" ] && [ "$repo" != "/etc/yum.repos.d/centos-all-mirrors.repo" ]; then
        mv "$repo" "$repo.bak"
    fi
done

echo "清理 yum 缓存..."
yum clean all

echo "更新缓存..."
if ! yum makecache; then
    echo "警告：缓存更新遇到问题，尝试使用单个镜像源..."
    # 如果多镜像源失败，尝试使用单个镜像源
    sed -i 's|^baseurl=.*|baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/os/x86_64/|' /etc/yum.repos.d/centos-all-mirrors.repo
    sed -i '/baseurl=.*/d' /etc/yum.repos.d/centos-all-mirrors.repo
    sed -i '/\[updates\]/,/\[.*\]/ s|^baseurl=.*|baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/updates/x86_64/|' /etc/yum.repos.d/centos-all-mirrors.repo
    sed -i '/\[extras\]/,/\[.*\]/ s|^baseurl=.*|baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/extras/x86_64/|' /etc/yum.repos.d/centos-all-mirrors.repo
    yum clean all
    yum makecache
fi

echo "查看配置的仓库列表："
yum repolist

echo "测试仓库可用性..."
if yum --disablerepo="*" --enablerepo="base" list available > /dev/null 2>&1; then
    echo "✅ 镜像源配置成功！"
else
    echo "❌ 镜像源配置可能有问题，请检查网络连接"
    echo "如需恢复原配置，请运行: cp $BACKUP_DIR/*.repo /etc/yum.repos.d/"
    exit 1
fi

# 可选：安装常用工具
echo "安装常用工具..."
if yum install -y curl wget vim; then
    echo "✅ 常用工具安装完成"
else
    echo "⚠️  常用工具安装失败，但镜像源配置已完成"
fi

echo "=========================================="
echo "CentOS 7 镜像源配置完成！"
echo "系统版本: CentOS $CENTOS_VERSION"
echo "备份位置: $BACKUP_DIR"
echo ""
echo "当前使用的镜像源:"
echo "✅ 清华大学镜像站 (tuna)"
echo "✅ 华为云镜像站" 
echo "✅ 阿里云镜像站"
echo "✅ 北京外国语大学镜像站"
echo "✅ EPEL 附加仓库"
echo ""
echo "故障排除:"
echo "如果遇到软件包找不到的问题，可以尝试启用 vault 源:"
echo "  yum --enablerepo=base-vault,updates-vault [command]"
echo "=========================================="

# 显示系统信息
echo ""
echo "系统信息:"
echo "CentOS 版本: $CENTOS_VERSION"
echo "内核版本: $(uname -r)"
echo "架构: $(uname -m)"